using System.Collections;
using System.ComponentModel;
using Microsoft.Win32;

namespace SharpService.Installer
{
    [RunInstaller(true)]
    public class WinServiceInstaller : System.Configuration.Install.Installer
    {
        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;

        private System.ServiceProcess.ServiceInstaller serviceInstaller1;

        public WinServiceInstaller()
        {
            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
            this.serviceProcessInstaller1.Password = null;
            this.serviceProcessInstaller1.Username = null;
            this.Installers.AddRange(new System.Configuration.Install.Installer[]
                                         {
                                             this.serviceProcessInstaller1,
                                             this.serviceInstaller1
                                         });
        }

        protected override void OnBeforeInstall(IDictionary savedState)
        {
            base.OnBeforeInstall(savedState);
            serviceInstaller1.ServiceName = this.Context.Parameters["name"];
        }

        public override void Install(IDictionary stateServer)
        {
            base.Install(stateServer);
            SetupParameters(new string[0]);
        }

        /// <summary>
        /// Uninstall based on the service name
        /// </summary>
        /// <PARAM name="savedState"></PARAM>
        protected override void OnBeforeUninstall(IDictionary savedState)
        {
            base.OnBeforeUninstall(savedState);

            // Set the service name based on the command line
            serviceInstaller1.ServiceName = this.Context.Parameters["name"];
        }

        private void SetupParameters(string[] pars)
        {
            //this.serviceInstaller1.
            // Define the registry keys
            // Navigate to services
            RegistryKey system = Registry.LocalMachine.OpenSubKey("System");
            RegistryKey currentControlSet = system.OpenSubKey("CurrentControlSet");
            RegistryKey services = currentControlSet.OpenSubKey("Services");
            // Add the service
            RegistryKey service =
                services.OpenSubKey(this.serviceInstaller1.ServiceName, true);

            string image = (string) service.GetValue("ImagePath");
            string config = Context.Parameters["config"];
            service.SetValue("ImagePath", image + " \"" + config + "\"");

            service.Close();
            services.Close();
            currentControlSet.Close();
            system.Close();
        }
    }
}